'''
山东航空
'''
import base64

import numpy as np
import requests
from PIL import Image

import model_precit
import util.img_utils as img_utils
import util.img_name_utils as img_name_utils
import model_type.sdhk.my_config as my_config
import os
import time


def init_img(file_path):
    img = Image.open(file_path)
    # 基本处理，灰度处理，提升识别准确率
    #     im = im.convert("L")
    return img

def get_next_width(img_np, start_index, end_index, threshold=180 * 3):
    s = -1
    e = end_index
    height, width = img_np.shape[0], img_np.shape[1]
    for x in range(start_index, end_index):
        has_thing = False
        for y in range(0, height):
            # print(img_np[x, y], x, y)
            # 非空白
            if sum(img_np[y, x]) <= threshold:
                # 还没开始
                if s == -1:
                    s = x
                has_thing = True
                break
            else:
                # 还没开始
                if s == -1:
                    continue
        if not has_thing and s != -1:
            e = x - 1
            break
    return s, e


def list_get_next_width(img_np, threshold=180 * 3):
    all_img_np = []
    s, e = get_next_width(img_np, 0, img_np.shape[1])
    while s != -1:
        if e - s > 3:
            all_img_np.append((s, e))
        s, e = get_next_width(img_np, e + 1, img_np.shape[1], threshold)
    # print(all_img_np)
    all_img_np2 = []
    for i in range(len(all_img_np)):
        s, e = all_img_np[i]
        # print(s, e, e - s)
        img = img_np[:, s:e + 1]
        all_img_np2.append(img)
    return all_img_np2


def get_next_height(img_np, start_index, end_index, threshold=180 * 3):
    s = -1
    e = end_index
    height, width = img_np.shape[0], img_np.shape[1]
    for x in range(start_index, end_index):
        has_thing = False
        for y in range(0, width):
            # print(img_np[x, y], x, y)
            # 非空白
            if sum(img_np[x, y]) <= threshold:
                # 还没开始
                if s == -1:
                    s = x
                has_thing = True
                break
            else:
                # 还没开始
                if s == -1:
                    continue
        if not has_thing and s != -1:
            e = x - 1
            break
    return s, e


def list_get_next_height(img_np, threshold=180 * 3):
    all_img_np = []
    s, e = get_next_height(img_np, 0, img_np.shape[0])
    while s != -1:
        # if e - s > 2:
        all_img_np.append((s, e))
        s, e = get_next_height(img_np, e + 1, img_np.shape[0], threshold)
    # print(all_img_np)
    all_img_np2 = []
    for i in range(len(all_img_np)):
        s, e = all_img_np[i]
        # print(s, e, e - s)
        img = img_np[s:e + 1:, ]
        all_img_np2.append(img)
    return all_img_np2


# def concatenate_width(img_nps):
#     return np.concatenate((img_nps), axis=1)

def concatenate_height(img_nps):
    return np.concatenate((img_nps), axis=0)


def cut_img(img):
    img_np = np.asarray(img).copy()
    threshold = 180 * 3
    img_np = img_utils.remove_noise(img_np, threshold)

    all_imgs_with_height = list_get_next_width(img_np, threshold)
    if len(all_imgs_with_height) > 4:
        # 删除最小宽度
        min_width = 0
        for i in range(1, len(all_imgs_with_height)):
            if all_imgs_with_height[min_width].shape[1] > all_imgs_with_height[i].shape[1]:
                min_width = i
        if all_imgs_with_height[min_width].shape[1] <= 5:
            all_imgs_with_height.pop(min_width)
        else:
            return []
    # all_imgs_with_height = concatenate_width(all_imgs_with_height)
    all_imgs = []
    for i in all_imgs_with_height:
        s = list_get_next_height(i, threshold)
        s = concatenate_height(s)
        img = Image.fromarray(s.astype('uint8')).convert("L")
        img = img_utils.resize(img, 32, 32).convert("L")
        all_imgs.append(img)
        # all_imgs.append(Image.fromarray(i.astype('uint8')))

    return all_imgs

def format_img(im, name, newFilepath='label/tmp'):
    '''
    格式化图片
    '''
    oldNameOld = name
    oldName = name.split('-')[0].split('.')[0].lower()

    if not os.path.exists(newFilepath):
        os.makedirs(newFilepath)
    nim = cut_img(im)
    if len(nim) == 0:
        print("{}:切割失败".format(oldNameOld))
        return
    # 格式化图片名
    name = img_name_utils.format_name(name)
    if len(nim) != len(name):
        name = ['z'] * len(nim)
    for i in range(len(nim)):
        nim[i].save(newFilepath + '/' + name[i] + '-' +
                    oldName + '_' + (str(time.time())).replace(".", "") + ".png", 'png')

def format_folder(filepath, newFilepath=None):
    '''
    格式化文件夹图片
    :param filepath:
    :param newFilepath:
    :return:
    '''
    if not newFilepath:
        newFilepath = 'label/tmp'
    fileList = os.listdir(filepath)
    for i in fileList:
        if '-' in i:
            im = Image.open(filepath + '/' + i)
            format_img(im, i, newFilepath)
        else:
            os.remove(filepath + '/' + i)
            print('删除不符合名称文件[{}]'.format(i))
    print('格式化完成')

def get_tag_img():
    """
    根据url获取合适的验证码
    :return:
    """
    r = requests.get(my_config.IMG_URL).content
    base64_str = base64.b64encode(r)
    base64_str = str(base64_str, 'utf8')
    # print(base64_str)
    im = img_utils.base64_to_image(base64_str)
    tag = model_precit.predict_img(im)
    if len(tag) == 0:
        return None, None
    return base64_str, tag


if __name__ == '__main__':
    # im = init_img('./img/1515-11.png')
    # ims = cut_img(im)
    # if len(ims) == 0:
    #     print("切割失败")
    # for i in range(len(ims)):
    #     print(i)
    #     ims[i].save('./test/{}.png'.format(i))

    # format_folder('label/old', 'label/tmp')
    img_utils.split_train_and_test('label/tmp', my_config.train_path, my_config.test_path, my_config.char_set)
